package com.xhh.nphm.web.controller.system;

import com.xhh.nphm.common.config.NphmConfig;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.utils.ServletUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.rsa.RSA;
import com.xhh.nphm.common.utils.rsa.RSAUtils;
import com.xhh.nphm.framework.shiro.UsernamePasswordToken;
import com.xhh.nphm.framework.web.service.ConfigService;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.ISmsService;
import com.xhh.nphm.system.service.ISysUserService;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.Map;

/**
 * 登录验证
 *
 * @author ydq
 */
@Controller
public class SysLoginController extends BaseController {
    /**
     * 是否开启记住我功能
     */
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;

    @Autowired
    private ConfigService configService;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISmsService smsService;

    private RSA rsa = new RSA();


    @GetMapping("${shiro.user.loginUrl2}")
    public String xlogin(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        mmap.put("copyrightYear", NphmConfig.getCopyrightYear());
//        HttpSession session = request.getSession();
//        //避免重复生成密钥
//        if(session.getAttribute("publicKey")==null){
//            // 创建密钥对
//            Map<String, String> keys = RSAUtils.createKeys(1024);
//            // 从Map中获取公钥
//            String publicKey = keys.get("publicKey");
//            String privateKey = keys.get("privateKey");
//            session.setAttribute("publicKey",publicKey);
//            session.setAttribute("privateKey",privateKey);
//        }
        return "login";
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        mmap.put("copyrightYear", NphmConfig.getCopyrightYear());
//        HttpSession session = request.getSession();
//        //避免重复生成密钥
//        if(session.getAttribute("publicKey")==null){
//            // 创建密钥对
//            Map<String, String> keys = RSAUtils.createKeys(1024);
//            // 从Map中获取公钥
//            String publicKey = keys.get("publicKey");
//            String privateKey = keys.get("privateKey");
//            session.setAttribute("publicKey",publicKey);
//            session.setAttribute("privateKey",privateKey);
//        }
        return "signin";
    }


    @GetMapping("/signin")
    public String signIn(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        mmap.put("copyrightYear", NphmConfig.getCopyrightYear());
//        HttpSession session = request.getSession();
//        //避免重复生成密钥
//        if(session.getAttribute("publicKey")==null){
//            // 创建密钥对
//            Map<String, String> keys = RSAUtils.createKeys(1024);
//            // 从Map中获取公钥
//            String publicKey = keys.get("publicKey");
//            String privateKey = keys.get("privateKey");
//            session.setAttribute("publicKey",publicKey);
//            session.setAttribute("privateKey",privateKey);
//        }
        return "signin";
    }

    /**
     *
     * @param username
     * @param password
     * @param rememberMe
     * @param modAct 0使用页面输入的分机号
     * @param tbSubTel 分机号
     * @param tbEqu 1硬话机 -1软话机
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe, String modAct, String tbSubTel, Integer tbEqu, HttpSession session) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 后端获取私钥
        Object privateKeyObj = session.getAttribute("privateKey");
        String privateKey = privateKeyObj == null ? null : privateKeyObj.toString();
        // 获得RSA类型的私钥
        RSAPrivateKey rsaPrivateKey = RSAUtils.getPrivateKey(privateKey);
        //私钥解密
        String decryptPassword = RSAUtils.privateDecrypt(password,rsaPrivateKey);
        UsernamePasswordToken token = new UsernamePasswordToken(username, decryptPassword, rememberMe);
        //获取随机分机号
//        tbSubTel = commonDao.fetchRandomTklTNo();
        token.setTbSubTel(tbSubTel);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser currentUser = ShiroUtils.getSysUser();
            session.setAttribute("ssnObjUser", currentUser);
            if("0".equals(modAct)) {
                currentUser.setTklTNo(tbSubTel);
            }
            currentUser.setFlagInt(tbEqu);
            ShiroUtils.setSysUser(currentUser);
            CommonServiceImpl.clearCatch();
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }

    /**
     * 获取手机验证码
     * @param mobile
     * @return
     */
    @PostMapping("/getSmsCode")
    @ResponseBody
    public AjaxResult getSMSCode(@RequestParam("phonenumber") String mobile) {
        String smsCode = smsService.getSmsCode(mobile);
        if (!smsCode.equals("0")) {
            return error(smsCode);
        }
        return success();
    }

    /**
     * 手机号登录
     * @param username
     * @param password
     * @param rememberMe
     * @param phonenumber
     * @param smsCode
     * @param session
     * @return
     */
    @PostMapping("/signin")
    @ResponseBody
    public AjaxResult phonenumberLogin(String username, String password, Boolean rememberMe, String phonenumber, String smsCode, HttpSession session) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 后端获取私钥
        Object privateKeyObj = session.getAttribute("privateKey");
        String privateKey = privateKeyObj == null ? null : privateKeyObj.toString();
        // 获得RSA类型的私钥
        RSAPrivateKey rsaPrivateKey = RSAUtils.getPrivateKey(privateKey);
        //私钥解密
        String decryptPassword = RSAUtils.privateDecrypt(password,rsaPrivateKey);
        String verifySMSCode = smsService.verifySMSCode(phonenumber, smsCode);
        if (!verifySMSCode.equals("success")) {
            return error(verifySMSCode);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, decryptPassword, rememberMe);
        //设置手机号
        token.setPhonenumber(phonenumber);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser currentUser = ShiroUtils.getSysUser();
            session.setAttribute("ssnObjUser", currentUser);
            ShiroUtils.setSysUser(currentUser);
            CommonServiceImpl.clearCatch();
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    /**
     * 校验是否有该用户
     * @param signInNo
     * @return
     */
    @GetMapping("/checkSignInNo")
    @ResponseBody
    public AjaxResult checkSignInNo(String signInNo){
        if(StringUtils.isNotNull(signInNo)){
            SysUser sysUser = sysUserService.selectUserByLoginName(signInNo);
            if (StringUtils.isNotNull(sysUser)) {
                return AjaxResult.success("用户存在",sysUser.getPhonenumber());
            }
        }
        return error("用户不存在");
    }


    /**
     * 校验是否有该用户
     * @param signInNo
     * @return
     */
    @GetMapping("/checkMobileCode")
    @ResponseBody
    public AjaxResult checkMobileCode(String signInNo, String userMobile, String userCode){
        String s = "";
        if(StringUtils.isNotNull(signInNo)){
             s = smsService.verifySMSCode(userMobile, userCode);
            if (!s.equals("success")) {
                return error(s);
            }
        }
        return success(s);
    }

    /**
     * 重置密码
     * @param resetUsername
     * @param newPassword
     * @return
     */
    @PostMapping("/resetPassword")
    @ResponseBody
    public AjaxResult resetPassword(String resetUsername,String newPassword, HttpSession session) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 后端获取私钥
        Object privateKeyObj = session.getAttribute("privateKey");
        String privateKey = privateKeyObj == null ? null : privateKeyObj.toString();
        // 获得RSA类型的私钥
        RSAPrivateKey rsaPrivateKey = RSAUtils.getPrivateKey(privateKey);
        //私钥解密
        String decryptNewPassword = RSAUtils.privateDecrypt(newPassword,rsaPrivateKey);
        SysUser user = sysUserService.selectUserByLoginName(resetUsername);
        if(user != null){
            user.setPassword(decryptNewPassword);
            user.setUpdateBy(user.getUserName());
            user.setUpdateTime(new Date());
            user.setPwdUpdateDate(new Date());
            if (sysUserService.resetUserPwd(user)>0) {
                return success();
            }
        }
        return error("重置失败，请重试");
    }

    /**
     * 获取密钥
     */
    @PostMapping("/getKeys")
    @ResponseBody
    public AjaxResult getKeys(HttpServletRequest request){
        HttpSession session = request.getSession();
        String publicKey=null;
        if(session.getAttribute("publicKey")==null) {
            // 创建密钥对
            Map<String, String> keys = RSAUtils.createKeys(1024);
            // 从Map中获取公钥
            publicKey = keys.get("publicKey");
            String privateKey = keys.get("privateKey");
            session.setAttribute("publicKey", publicKey);
            session.setAttribute("privateKey", privateKey);
        }else{
            publicKey = session.getAttribute("publicKey").toString();
        }
        if (publicKey==null){
            return error("密钥获取失败");
        }
        return success(publicKey);
    }

}
